package summer.codegenerator.common.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import summer.codegenerator.Constant;

/**
 * 
 *
 * @author jiangz
 * @version 1.0 Created on 2019年7月29日 上午10:36:06
 */
public class CookieUtil {

	/**
	 * get cookie
	 *
	 * @param request		请求
	 * @param name			cookie name
	 * @return cookie
	 */
	public static Cookie getCookieByName(HttpServletRequest request, String name) {
		Map<String, Cookie> cookieMap = getCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie = (Cookie) cookieMap.get(name);
			return cookie;
		} else {
			return null;
		}
	}

	/**
	 * save cookie
	 *
	 * @param response		响应
	 * @param name			cookie name
	 * @param value			cookie value
	 * @param time			存活时间（分钟）
	 */
	public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int maxAge) {
		Cookie cookie = new Cookie(name, value);
		cookie.setPath(Constant.COOKIE_PATH);
		try {
			URLEncoder.encode(value, Constant.CHARACTERS_SET);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		cookie.setMaxAge(maxAge * 60);
		response.addCookie(cookie);
		return response;
	}

	/**
	 * delete cookie
	 *
	 * @param request		请求
	 * @param response		响应
	 * @param name			cookie name
	 */
	public static void deleteCookieByName(HttpServletRequest request, HttpServletResponse response, String name)
			throws NullPointerException {
		Map<String, Cookie> cookieMap = getCookieMap(request);
		if(cookieMap.containsKey(name)) {
			Cookie cookie = cookieMap.get(name);
			cookie.setMaxAge(0);
			cookie.setPath(Constant.COOKIE_PATH);
			response.addCookie(cookie);
		}
	}
	
	private static Map<String, Cookie> getCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		return cookieMap;
	}
}
